package com.android.xcalendar.util;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.HttpProtocolParams;

import android.util.Log;

public class XCalendarAPIManager {
	public static final String LOG_TAG = "XCalendarAPIManager";
	public static XCalendarAPIManager uniqueInstance;

	public static XCalendarAPIManager getInstance() {
		if (uniqueInstance == null) {
			uniqueInstance = new XCalendarAPIManager();
			return uniqueInstance;
		}
		return uniqueInstance;
	}

	public String connect(String url) {

		HttpResponse resp = null;
		String resultBody = "";

		final HttpClient asyncClient = new DefaultHttpClient();

		HttpProtocolParams.setUseExpectContinue(asyncClient.getParams(), false);

		final HttpGet httpGet = new HttpGet(url);

		Log.d(LOG_TAG, "Request URL = " + url);

		// execute HTTP Get Request
		try {
			resp = asyncClient.execute(httpGet);
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}

		if (resp == null) {
			Log.d(LOG_TAG, "Response Null");
			return "";
		}
		// read response body

		HttpEntity entity = resp.getEntity();

		if (entity != null) {

			try {
				InputStream instream = entity.getContent();
				resultBody = convertStreamToString(instream);
			} catch (IllegalStateException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}

		}

		Log.d(LOG_TAG, "Response CODE = "
				+ resp.getStatusLine().getStatusCode() + " DATA = "
				+ resultBody);
		return resultBody;
	}

	private static String convertStreamToString(InputStream is) {

		BufferedReader reader = new BufferedReader(new InputStreamReader(is));
		StringBuilder sb = new StringBuilder();

		String line = null;
		try {
			while ((line = reader.readLine()) != null) {

				sb.append(line + "\n");
			}
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				is.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return sb.toString();
	}

}
